package org.hbhk.hms.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hbhk.hms.entity.HmsTopic;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;

@Service
public class SqlUtil {

	/**
	 * private Long id;
	 * 
	 * private String mqName;
	 * 
	 * private String targetTopic;
	 * 
	 * private String msg;
	 * 
	 * private String msgKey;
	 * 
	 * private String tags;
	 * 
	 * private Long delay;
	 * 
	 * private Date delayTime;
	 * 
	 * private Integer status;
	 * 
	 * private Date createTime;
	 * 
	 * @throws SQLException
	 * 
	 */

	private String cols = "id,mq_name,target_topic,msg,msg_key,tags,delay,delay_time,status,create_time";

	public void executeInsert(JdbcTemplate jdbcTemplate, String recordTable, List<HmsTopic> records) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = jdbcTemplate.getDataSource().getConnection();

			StringBuilder batchSql = new StringBuilder("INSERT INTO ");
			batchSql.append(recordTable).append("(" + cols + ") VALUES ")
					.append(StringUtils.repeat("(?,?,?,?,?,?,?,?,?,?),", records.size()));

			Object[] parameters = FluentIterable.from(records)
					.transformAndConcat(new Function<HmsTopic, Iterable<Object>>() {
						@Override
						public Iterable<Object> apply(HmsTopic mqRecord) {
							return Lists.newArrayList(mqRecord.getId(), mqRecord.getMqName(), mqRecord.getTargetTopic(),
									mqRecord.getMsg(), mqRecord.getMsgKey(), mqRecord.getTags(), mqRecord.getDelay(),
									mqRecord.getDelayTime(), mqRecord.getStatus(), mqRecord.getCreateTime());
						}
					}).toArray(Object.class);

			ps = conn.prepareStatement(batchSql.substring(0, batchSql.length() - 1));
			for (int i = 0; i < parameters.length; i++) {
				ps.setObject(i + 1, parameters[i]);
			}
			int count = ps.executeUpdate();
			Assert.isTrue(count == records.size(), "insert batch failed");
		} catch (SQLException e) {
			JdbcUtils.closeStatement(ps);
			DataSourceUtils.releaseConnection(conn, jdbcTemplate.getDataSource());
			throw new RuntimeException("insert batch failed", e);
		} finally {
			JdbcUtils.closeStatement(ps);
			DataSourceUtils.releaseConnection(conn, jdbcTemplate.getDataSource());

		}
	}
}
